package com.example.arithmeticleetcode.leetcode.dec;

import java.util.*;

/**
 * @program: arithmetic-leetcode
 * @description:
 * @author: FangZhen
 * @create: 2020-12-09 09:51
 **/
public class Demo04 {

    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>();
        list.add(1);
        list.add(1);
        list.add(2);
        list.add(1);
        System.out.println(list);
        list.remove(1);
        System.out.println(list);


        int[] arr = {1, 2, 3, 4};
        System.out.println(maxOperations(arr,5));

        int[] arr2 = {1, 1, 1, 1};
        System.out.println(maxOperations(arr2,2));
    }

    public static int maxOperations(int[] nums, int k) {
        int count = 0;
        Map<Integer, Integer> map = new HashMap<>();

        for (int num : nums) {
            map.put(num, map.getOrDefault(num, 0) + 1);
        }

        List<Integer> list = new ArrayList<>();
        Iterator<Map.Entry<Integer, Integer>> iterator = map.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<Integer, Integer> entry = iterator.next();
            if (list.contains(entry.getKey())) continue;
            int tempKey = k - entry.getKey();
            if (tempKey == entry.getKey()) {
                count += (entry.getValue() >> 1);
                continue;
            }
            if (map.containsKey(tempKey)) {
                int value = map.get(tempKey);
                count += entry.getValue() > value ? value : entry.getValue();
                list.add(tempKey);
            }
            iterator.remove();
        }
        return count;
    }
}
